package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.common.redis.CacheService;
import com.heima.file.service.FileStorageService;
import com.heima.utils.baidu.Base64Util;
import com.heima.utils.baidu.HttpUtil;
import com.heima.wemedia.service.BaiDuScanService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author 陈辉
 * @data 2023 10:21
 */
@Service
@Slf4j
public class BaiDuScanServiceImpl implements BaiDuScanService {
    @Autowired
    private CacheService cacheService;
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 百度云文本审核
     *
     * @param text
     * @return 1：合规; 2: 不合规; 3: 疑似
     */
    @Override
    public int scanText(String text) {

        //定义一个标记位：默认返回人工处理
        int res = 3;

        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        try {
            String param = "text=" + URLEncoder.encode(text, "utf-8");

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            //从redis中拿access_token
            String accessToken = cacheService.get("access_token");
            if (StringUtils.isBlank(accessToken)){
                //手动调用生成token方法来获取一次token
                accessToken = refreshToken();
            }

            String result = HttpUtil.post(url, accessToken, param);
            log.info(result);

            JSONObject jsonObject = JSONObject.parseObject(result);
            String conclusionType = jsonObject.getString("conclusionType");
            if (StringUtils.isNotBlank(conclusionType)){
                res = Integer.parseInt(conclusionType);
                if (res == 4)res = 2;
                return res;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return res;
    }

    /**
     * 百度云图片审核
     *
     * @param path
     * @return 1：合规; 2: 不合规; 3: 疑似
     */
    @Override
    public int scanImg(String path) {
        //定义一个标记位：默认返回人工处理
        int res = 3;
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined";
        try {
            byte[] imgData = fileStorageService.downLoadFile(path);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            //从redis中拿access_token
            String accessToken = cacheService.get("access_token");
            if (StringUtils.isBlank(accessToken)){
                //手动调用生成token方法来获取一次token
                accessToken = refreshToken();
            }

            String result = HttpUtil.post(url, accessToken, param);
            log.info(result);

            JSONObject jsonObject = JSONObject.parseObject(result);
            String conclusionType = jsonObject.getString("conclusionType");
            if (StringUtils.isNotBlank(conclusionType)){
                res = Integer.parseInt(conclusionType);
                if (res == 4)res = 2;
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return res;
    }

    //定时刷新access_token： 每10天执行一次
    @Scheduled(cron = "0 0 0 1/10 * ? ")
    private String refreshToken(){
        try {
            OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token?client_id=yOI74EgIcKZtlE98Y8UH2DVI&client_secret=ivnBMFww4skFTXN7kAIQueUMR7h7VGbL&grant_type=client_credentials")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            String responseJson = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(responseJson);

            String accessToken = jsonObject.getString("access_token");


            //将accessToken存入redis管理
            cacheService.set("access_token",accessToken);

            return accessToken;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
